<template>
  <div class="app-container">
    <!-- 主要内容区 -->
    <main class="main-content">
      <div class="container">
        <h1 class="page-title">我的订单</h1>

        <!-- 订单筛选 -->
        <div class="order-filters">
         <button
            :class="{ active: filterStatus === 'all' }"
            @click="filterStatus = 'all'"
          >
            全部订单
          </button>
          <button
            :class="{ active: filterStatus === 'paid' }"
            @click="filterStatus = 'paid'"
          >
            已支付
          </button>
          <button
            :class="{ active: filterStatus === 'unpaid' }"
            @click="filterStatus = 'unpaid'"
          >
            待支付
          </button>
          <button
            :class="{ active: filterStatus === 'canceled' }"
            @click="filterStatus = 'canceled'"
          >
            已取消
          </button>
          <button
            :class="{ active: filterStatus === 'refunded' }"
            @click="filterStatus = 'refunded'"
          >
            已退票
          </button>

        </div>

        <!-- 订单列表 -->
        <div class="orders-list">
          <!-- 加载状态 -->
          <div v-if="loading" class="loading-state">加载中...</div>

          <!-- 订单卡片 - 动态渲染所有订单 -->
          <div class="order-card" v-for="order in orders" :key="order.orderId">
            <div class="order-header">
              <span class="order-date">{{ formatDate(order.orderTime) }}</span>
              <span class="order-no">订单号: {{ order.orderNumber }}</span>
            </div>

            <div class="order-content">
              <img
                :src="order.movie?.poster || defaultPoster"
                alt="电影海报"
                class="movie-poster"
              />

              <div class="movie-info">
                <h3 class="movie-title">
                  {{ order.movie?.title || "未知电影" }}
                </h3>
                <p class="cinema">{{ order.movie?.cinema || "未知影院" }}</p>
                <p class="hall-seat">
                  {{ order.movie?.hall || "未知影厅" }}
                  {{ order.seatCoordinates || "未知座位" }}
                </p>
                <p class="movie-time">
                  {{ order.movie?.time || order.orderTime || "未知时间" }}
                </p>
                <p v-if="order.couponAmount > 0" class="coupon-info">
                  使用优惠券: {{ order.couponName }} (抵扣 ¥{{
                    order.couponAmount
                  }})
                </p>
                <p class="pay-timeout" v-if="order.statues === 0">
                  <i class="warning-icon">⚠️</i>
                  剩余15分钟未支付将自动取消
                </p>
              </div>

              <div class="price-status">
                <div class="order-price">¥{{ order.finalPrice }}</div>
                <div
                  class="order-status"
                  :class="{
                    paid: order.statues === 1,
                    unpaid: order.statues === 0,
                    refunded: order.statues === 2,
                  }"
                >
                  {{ getStatusText(order.statues) }}
                </div>
              </div>

              <div class="action-buttons">
                <button
                  v-if="order.statues === 0"
                  class="pay-btn"
                  @click="handlePay(order)"
                >
                  付款
                </button>
                <button
                  v-if="order.statues === 1"
                  class="refund-btn"
                  @click="handleRefund(order)"
                >
                  申请退票
                </button>
                <button class="detail-btn" @click="handleViewDetail(order)">
                  查看详情
                </button>
              </div>
            </div>
          </div>

          <!-- 空状态提示 -->
          <div class="empty-state" v-if="!loading && orders.length === 0">
            <div class="empty-icon">📭</div>
            <p class="empty-text">暂无符合条件的订单</p>
            <button class="empty-action" @click="changeNav('movies')">
              去购票
            </button>
          </div>
        </div>
      </div>
    </main>

    <!-- 页脚 -->
    <footer class="main-footer">
      <div class="container">
        <p class="copyright">© 2025 荏闻电影 版权所有</p>
      </div>
    </footer>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import { useRouter } from "vue-router";
import { getOrdersByUserId } from "@/api/user";

import { submitRefund } from "@/api/user";

const router = useRouter();

// 格式化日期
// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return "未知日期";

  // 转换为 JavaScript Date 对象
  const date = new Date(dateString);

  // 检查日期是否有效
  if (isNaN(date)) return "无效日期";

  // 格式化为 "YYYY-MM-DD HH:MM" 格式
  const formatted = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")} ${String(
    date.getHours()
  ).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;

  return formatted;
};



// 导航状态
const currentNav = ref("orders");
const userMenuVisible = ref(false);
const filterStatus = ref("all");
const orders = ref([]);
const loading = ref(false);
// 默认海报图，避免图片加载失败
const defaultPoster = "https://picsum.photos/120/160";

// 状态映射关系：前端状态 -> 后端状态码
const statusMap = {
  all: null,     // 全部
  paid: 1,       // 已支付
  unpaid: 0,     // 待支付
  refunded: 2,   // 已退票
  canceled: 3    // 已取消
};

// 监听筛选状态变化
watch(filterStatus, (newVal) => {
  console.log(`筛选状态变更为: ${newVal} (对应后端状态码: ${statusMap[newVal]})`);
});

// 获取订单状态文本
const getStatusText = (statusCode) => {
  const statusMap = {
    1: "已支付",
    0: "待支付",
    3: "已取消",
    2: "已退票"
  };
  const text = statusMap[statusCode] || "未知状态";
  console.log(`状态码 ${statusCode} 转换为文本: ${text}`);
  return text;
};

// 获取订单数据
const fetchOrders = async () => {
  const userId = localStorage.getItem("userId");
  console.log(`✅ 开始获取订单，用户ID: ${userId}`);

  if (!userId) {
    alert("请先登录");
    router.push("/login");
    return;
  }

  loading.value = true;
  try {
    // 获取订单数据
    const res = await getOrdersByUserId(userId);
    
    // 打印原始的 response 返回结果
    console.log("🔍 后端原始订单返回数据:", res);

    // ✅ 正确读取数组位置：res.data.data
    const list = res.data?.data;
    if (!Array.isArray(list)) {
      console.warn("⚠️ 后端 data.data 不是数组，清空 orders");
      orders.value = [];
      return;
    }

    console.log(`📦 收到订单数组，共 ${list.length} 条`);

    // 直接映射订单字段（你现在后端返回就是扁平结构，不是二级结构）
    let mapped = list.map((item) => ({
       orderId: item.orderId || "",
      orderNumber: item.orderNumber || "",
      orderTime: item.orderTime || "",
      finalPrice: item.finalPrice || 0,
      originalPrice: item.originalPrice || 0,
      seatCoordinates: item.seatCoordinates || "",
      // 补充优惠券相关字段
  couponValue: item.couponValue || 0,  
  couponName: item.couponName || "",    
  serviceFee: item.serviceFee || 5,     // 补充服务费字段
      movie: {
        title: item.movieName || "未知电影",
        poster: item.movieImage || defaultPoster,
        cinema: item.cinemaName || "未知影院",
        hall: item.hallNumber || "未知影厅",
        time: item.startTime || "未知时间",
      },
      statues: item.statues, // ❗保留状态用于过滤
    }));

    // 前端筛选状态
    if (filterStatus.value !== "all") {
      const statusCode = statusMap[filterStatus.value];
      mapped = mapped.filter(o => o.statues === statusCode);
      console.log(`🎯 筛选状态 ${filterStatus.value}(${statusCode}) -> ${mapped.length} 条`);
    }

    orders.value = mapped;
    console.log("✅ 最终渲染订单：", orders.value);

  } catch (err) {
    console.error("❌ 获取订单失败:", err);
    alert("获取订单失败，请稍后再试");
  } finally {
    loading.value = false;
  }
};

// 初始加载和状态变化时重新获取订单
onMounted(() => {
  console.log("我的订单页面挂载，开始加载订单数据");
  fetchOrders();
});
watch(filterStatus, fetchOrders);

// 导航切换
const changeNav = (nav) => {
  console.log(`导航切换至: ${nav}`);
  if (nav === "movies") {
    router.push("/reying");
  }
};
// 查看订单详情
const handleViewDetail = (order) => {
  console.log(`查看订单详情: ${order.orderNumber}`);
  // 跳转到订单详情页
  router.push({
    path: "/order-detail",
    query: {
      orderData: JSON.stringify({
        orderId: order.orderId,
        orderNumber: order.orderNumber,
        finalPrice: order.finalPrice,
        originalPrice: order.originalPrice,
        movieName: order.movie?.title || "未知电影",
        hall: order.movie?.hall || "未知影厅",
        time: order.movie?.time || order.orderTime || "未知时间",
        seats: order.seatCoordinates?.split(",") || [],
        status: getStatusText(order.statues),
        serviceFee: order.serviceFee || 5,
       // 优惠券相关字段
        couponAmount: order.couponValue  || 0,
        couponName: order.couponName || "",
        // 其他必要字段
        cinemaName: order.movie?.cinema || "未知影院",
        statues: order.statues,
        orderTime: order.orderTime,
        movieImage: order.movie?.poster || defaultPoster,
        ticketCode: order.ticketCode,
        ticketCount: order.ticketCount
      }),
      moviePoster: order.movie?.poster || defaultPoster,
    },
  });
};

// 处理退票
const handleRefund = (order) => {
  console.log(`跳转到退票页面，订单ID: ${order.orderId}`, order);

  // 获取用户ID
  const userId = localStorage.getItem("userId");

  // 验证参数
  if (!userId || !order.orderId) {
    alert("订单信息不完整，无法提交退票");
    return;
  }

  // 跳转到退票确认页面（Refund.vue），并传递必要参数
  router.push({
    path: "/refund", // 假设Refund.vue的路由路径是/refund
    query: {
      orderId: order.orderId,
      orderNumber: order.orderNumber,
      movieName: order.movie?.title || "未知电影",
      finalPrice: order.finalPrice,
      userId: userId,
    },
  });
};

</script>

<style>
/* 样式部分保持不变 */
.app-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f9f9f9;
}

.main-content {
  flex: 1;
  padding: 30px 0;
}

.container {
  width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-title {
  font-size: 24px;
  margin-bottom: 20px;
  color: #333;
}

.order-filters {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.order-filters button {
  padding: 8px 16px;
  background-color: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.order-filters button.active {
  background-color: #a2131d;
  color: white;
  border-color: #a2131d;
}

.orders-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.order-card {
  background-color: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  font-size: 14px;
  color: #666;
}

.order-content {
  display: flex;
  gap: 15px;
}

.movie-poster {
  width: 80px;
  height: 110px;
  object-fit: cover;
  border-radius: 4px;
}

.movie-info {
  flex: 1;
  min-width: 0;
}

.movie-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.cinema,
.hall-seat,
.movie-time,
.coupon-info {
  margin: 0 0 5px 0;
  font-size: 13px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.coupon-info {
  color: #a2131d;
}

.pay-timeout {
  margin: 5px 0 0 0;
  font-size: 12px;
  color: #ff9800;
  display: flex;
  align-items: center;
}

.warning-icon {
  margin-right: 4px;
}

.price-status {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: flex-end;
  min-width: 100px;
}

.order-price {
  font-size: 16px;
  font-weight: bold;
  color: #a2131d;
}

.order-status {
  font-size: 14px;
  padding: 3px 8px;
  border-radius: 4px;
}

.order-status.paid {
  background-color: #e8f5e9;
  color: #4caf50;
}

.order-status.unpaid {
  background-color: #fff8e1;
  color: #ff9800;
}

.order-status.refunded {
  background-color: #e3f2fd;
  color: #2196f3;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-width: 80px;
}

.pay-btn,
.refund-btn,
.detail-btn {
  padding: 6px 0;
  border-radius: 4px;
  font-size: 13px;
  cursor: pointer;
  border: none;
}

.pay-btn {
  background-color: #a2131d;
  color: white;
  margin-top: 75px;
}

.refund-btn {
  background-color: #f5f5f5;
  color: #333;
}

.detail-btn {
  background-color: white;
  color: #666;
  border: 1px solid #ddd;
}

.loading-state {
  text-align: center;
  padding: 50px 0;
  color: #666;
  font-size: 16px;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 15px;
  color: #ddd;
}

.empty-text {
  margin: 0 0 20px 0;
  color: #666;
  font-size: 16px;
}

.empty-action {
  padding: 10px 20px;
  background-color: #a2131d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.main-footer {
  background-color: #333;
  color: white;
  padding: 20px 0;
  margin-top: 50px;
}

.copyright {
  margin: 0;
  text-align: center;
  font-size: 14px;
  color: #aaa;
}

@media (max-width: 768px) {
  .container {
    width: 100%;
  }

  .order-content {
    flex-direction: column;
  }

  .price-status {
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    margin-top: 10px;
    min-width: auto;
    width: 100%;
  }

  .action-buttons {
    flex-direction: row;
    justify-content: flex-end;
    width: 100%;
    margin-top: 10px;
  }

  .pay-btn,
  .refund-btn,
  .detail-btn {
    padding: 6px 12px;
  }
}
</style>